package com.hfxt.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

//@Configuration
//@EnableTransactionManagement
public class SqlSessionFactoryConfig {

    //创建工厂对象
    //DataSource自动读取application.properties中的参数，并且实例由springboot自动创建，所以可以进行注入
    /*@Bean对应的方法，参数可以作为创建类的属性进行注入（参数已经由springboot创建了实例）
    返回值类型就是需要的bean的类型
    方法名 就是bean的name，根据name可以获取到该实例；可以在@Bean后面加上名称进行修改
    方法体如何编写：
        创建指定的实例对象；
        然后注入属性；
        将创建的实例使用return进行返回
     */
//    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hfxt.entity");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));
            return sqlSessionFactoryBean.getObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //MapperScannerConfigurer
//    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.hfxt.mapper");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }
}
